package com.hy.main.demo.io;

import lombok.AllArgsConstructor;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @Author yang DongYong
 * @Date 2022/4/26 - 04 - 26 - 22:35
 * @Description: com.hy.main.demo.file
 * @version: 1.0
 */
public class ObjectsOutPutStreams {

    /**
     * 用流的形式序列化保存对象
     * 往文件写入数据称为序列化，读取数据称为反序列化
     */
    @Test
    public void OutputFile() {
        // 被序列化的对象只能以.dat结尾
        String path = "e:\\dog.dat";
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
            // 传入的类一定要实现Serializable接口 否则会抛出运行时异常
            objectOutputStream.writeObject(new Dog(1, "旺财"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

@AllArgsConstructor
class Dog implements Serializable {
    private Integer id;

    private String name;
}
